<?php
/**
* 订单模块 工具类
*
* 订单模块 工具类的注意及说明
* 以下use模块请不要互相伤害
*
* @author    xiecz <xiecz@yunys.com.cn>
* @copyright 2016 QuanZhouYunYiShang Inc.
*/
namespace App\Services\Tool\Order;

use Illuminate\Support\Facades\Mail;
use App\Services\Tool\DataBase\SQL;
use Illuminate\Support\Facades\DB;
use Log, Auth;
use App\Services\Tool\GeneralTool;
use App\Services\Tool\CouponsTool;
use App\Services\Tool\Car\CarTool;
use App\Services\UserService\UserTool;
use App\Services\ProductTempService\ProductTempTool;
use App\Services\GiftService\GiftApiService;
use App\Services\ProductsService\ProductTool;
use App\Services\SourcePicService\SourcePicTool;
use App\Services\ImgServices\ImgTool;
use App\Services\Tool\Jpush\JpushTool;
use App\Services\Tool\Statistics\IncomeTool;
use Maatwebsite\Excel\Facades\Excel;
use App\Services\Tool\WxTemplate;
use App\Services\Tool\DataBase\DB_MYSQL_XCZ as ODB;

class OrderTool{

    function __construct(CarTool $carTool,
                         UserTool $userTool,
                         ProductTempTool $productTempTool,
                         GiftApiService $giftApiService,
                         ProductTool $productTool,
                         SourcePicTool $sourceTool){
        $this->carTool         = $carTool;
        $this->userTool        = $userTool;
        $this->productTempTool = $productTempTool;
        $this->giftApiService  = $giftApiService;
        $this->productTool     = $productTool;
        $this->sourceTool      = $sourceTool;
    }

    /**
        获取购物车下单详情
     */
    function get_shop_car_goods($input){
        $input['where'] = ['user_id'=>$input['user_id'],'state'=>1,'is_select'=>1];
        $shop_car       = $this->carTool->getShopCarList($input,2);
        $shop_car['total_fee'] += $shop_car['total_postage'];

        return $shop_car;
    }

    /**
        获取立即购买下单详情
     */
    function get_buy_immediately_submit_goods($input, $fee = []){
        $good  = $this->carTool->buy_immediately_submit_goods($input,2);
        /*
        if(isset($fee['product_current_price'])){
            foreach($good['goods']['vaild'] as $one){

            }
        }
        */
        $good['total_fee'] += $good['total_postage'];
        return $good;
    }

    /**
     * 获取活动作品金额
     */
    static function get_product_fee_active($input){
        $data['user_id'] = $input['user_id'];
        $data['product_id'] = $input['product_id'];
        $str = GeneralTool::createLinkstring($data);
        switch($input['channel_id']){
            case 'kanjia20170310':
                $url = env('WEI_SHOP_URL') . 'get-price';
                break;
            case 'septwolves20170316':
                $url = env('WEI_SHOP_URL') . 'septwolves-get-price';
                break;
            default:
                $url = env('WEI_SHOP_URL') . 'get-price';
        }

        $result = GeneralTool::http_curl($url, $str, 1);
        return $result;
    }

    /**
        生成订单
        type 1普通生成订单2活动生成订单
     */
    function create_order($shop_car, $input, $address, $coupon, $type = 1){

        $state = GeneralTool::createResult('','M00000');
        try{
            if($shop_car['total_fee'] < 0 ||
                ($shop_car['total_fee'] <=0 && !isset($coupon['discount'])) && $type == 1)
                return GeneralTool::createResult('','M05018');
            //生成订单orders
            $arr['order_id']      = GeneralTool::only_no();
            $arr['buyer_id']      = $input['user_id'];
            $arr['total_postage'] = $shop_car['total_postage'];
            $arr['total_fee']     = $shop_car['total_fee'];
            $arr['type']          = 'order';
            $arr['state']         = $shop_car['total_fee'] == 0 ? 2 : 1;
            $arr['platform']      = $this->order_platform($input['platform']);
            $arr['message']       = !isset($input['message']) || trim($input['message']) == '' ? '' : bin2hex($input['message']);
            $arr['back_message']  = '';
            $arr['substr']        = '';
            $arr['channel_id']    = isset($input['channel_id']) ? $input['channel_id'] : '';
            $arr['created_at']    = time();
            $arr['updated_at']    = $arr['created_at'];
            $orders = SQL::insert(['table'  => 'orders',
                                   'insert' => $arr]);
            if(!$orders) return GeneralTool::createResult('','M00001');

            //记录优惠券order_coupons
            $order_coupons = $this->insert_order_coupons($arr,$coupon);
            if(!$order_coupons){
                $state = GeneralTool::createResult('','M05004');
                Throw new \Exception("优惠券异常");
            }

            //记录收货地址order_express
            $order_express = $this->insert_order_express($arr,$address);
            if($order_express != 'M00000'){
                $state = GeneralTool::createResult('',$order_express);
                Throw new \Exception("记录收货信息失败");
            }

            //记录订单详情order_details(包含赠品)
            $order_details = $this->order_details($shop_car,$arr);
            if($order_details['state'] != 'M00000'){
                $state  = $order_details;
                Throw new \Exception("记录订单详情异常");
            }

            //清空购物车选中

            return ['result' => ['order_id'=>$arr['order_id']],'state'=>'M00000','message' => '下单成功'];
        }catch(\Exception $e){
             Log::info($e);
             SQL::CatchDo();
             return $state;
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        订单详情处理
     */
    function order_details($shop_car,$arr){

        foreach($shop_car['goods']['vaild'] as $good){
            //order_details
            $order_details = $this->insert_order_details($good,$arr);
            if($order_details['state'] != 'M00000') return $order_details;
            //order_gifts
            $order_gifts   = $this->insert_order_gifts($good,$arr);
            //order_detail_print
            $order_detail_print = $this->order_detail_print($good,$arr);
            if($order_detail_print != 'M00000') return GeneralTool::createResult('',$order_detail_print);
            //order_detail_fee
            $order_detail_fee = $this->order_detail_fee($good,$arr);
            if($order_detail_fee != 'M00000') return GeneralTool::createResult('',$order_detail_fee);
        }

        return GeneralTool::createResult('','M00000');

    }

    /**
        打印图明细
     */
    function order_detail_print($good, $arr, $type = 1){
        if($type == 1 && (!isset($good->product_preview_image_ids) || count($good->product_preview_image_ids) == 0))
            return 'M05052';
        foreach($good->product_preview_image_ids as $image){
            if(!isset($image->product_preview_image_id) || !isset($image->position_type))
                return 'M05052';
            $insert['print_picture_id'] = $image->product_preview_image_id;
            $insert['position_type']    = $image->position_type;
            $result                     = $this->insert_order_detail_print($insert, $good, $arr);
            if($result != 'M00000') return $result;
        }
        return 'M00000';
    }

    /**
        添加打印图
     */
    function insert_order_detail_print($insert, $good, $arr){
        $insert['order_id']   = $arr['order_id'];
        $insert['product_id'] = $good->product_id;
        $insert['created_at'] = time();
        $insert['updated_at'] = $insert['created_at'];
        if(SQL::count(['table' => 'order_detail_prints',
                       'where' => ['order_id'      => $insert['order_id'],
                                   'product_id'    => $insert['product_id'],
                                   'position_type' => $insert['position_type'],
                                   'state'         => 1]]))
            return 'M00000';
        $result               = SQL::insert(['table' => 'order_detail_prints',
                                             'insert'=> $insert]);
        return $result ? 'M00000' : 'M05053';
    }

    /**
        订单资费明细
     */
    function order_detail_fee($good,$arr){
        //模版
        $temp['product_id']         = $good->product_id;
        $temp['colour_name']        = $good->colour_name;
        $temp['size_name']          = $good->size_name;
        $temp['resource_id']        = $good->product_temp_id;
        $temp['type']               = 1;
        $temp['user_id']            = $good->product_temp->user_id;
        $temp['title']              = $good->product_temp->product_temp_name;
        $temp['preferential_price'] = $good->product_temp->preferential_price;
        $temp['quantity']           = $good->quantity;
        $temp['thumbnail']          = isset($good->product_temp->thumbnail) ? self::getImgPathByImgUrl($good->product_temp->thumbnail) : '';
        $temp_result         = $this->insert_order_detail_fee($temp,$arr);
        if($temp_result != 'M00000') return $temp_result;
        //溢价
        if($good->overflow_price > 0){
            $overflow['product_id']         = $good->product_id;
            $overflow['colour_name']        = $good->colour_name;
            $overflow['size_name']          = $good->size_name;
            $overflow['resource_id']        = $good->product_id;
            $overflow['type']               = 5;
            $overflow['user_id']            = $good->user_id;
            $overflow['title']              = '溢价';
            $overflow['preferential_price'] = $good->overflow_price;
            $overflow['quantity']           = $good->quantity;
            $overflow['thumbnail']          = isset($good->thumbnail[0]) ? GeneralTool::clearn_product_image_url($good->thumbnail[0]) : '';
            $temp_result         = $this->insert_order_detail_fee($overflow,$arr);
            if($temp_result != 'M00000') return $temp_result;
        }

        //素材
        //字体
        //工艺
        foreach($good->source_pics as $source){
            $sour['product_id']         = $good->product_id;
            $sour['colour_name']        = $good->colour_name;
            $sour['size_name']          = $good->size_name;
            $sour['resource_id']        = $source->source_pic_id;
            $sour['type']               = $this->order_detail_fee_type($source->type);
            $sour['user_id']            = isset($source->user_id) ? $source->user_id : '';
            $sour['title']              = $source->source_pic_name;
            $sour['preferential_price'] = $source->preferential_price;
            $sour['quantity']           = $good->quantity;
            $sour['thumbnail']          = isset($source->thumbnail) ? self::getImgPathByImgUrl($source->thumbnail) : '';
            $sour_result         = $this->insert_order_detail_fee($sour,$arr);
            if($sour_result != 'M00000') return $sour_result;
        }
        return 'M00000';
    }

    /**
        记录订单资费明细
     */
    function insert_order_detail_fee($ar, $arr){
        $ar['order_id']   = $arr['order_id'];
        $ar['created_at'] = time();
        $ar['updated_at'] = $ar['created_at'];

        $result = SQL::insert(['table'  => 'order_detail_fees',
                               'insert' => $ar]);
        return $result ? 'M00000' : 'M05015';
    }

    /**
        记录赠品
     */
    function insert_order_gifts($good,$arr){
        foreach($good->gift as $gift){
            /*
                减库存
                1. 赠品库存 - √
            */
            $gift_result = $this->giftDecrementStock(intval($gift->gift_id), intval($gift->quantity));

            if(!$gift_result) continue;

            $ar['order_id']       = $arr['order_id'];
            $ar['gift_id']        = $gift->gift_id;
            $ar['fg_id']          = $gift->fg_id;
            $ar['product_id']     = $good->product_id;
            $ar['colour_name']    = $good->colour_name;
            $ar['size_name']      = $good->size_name;
            $ar['name']           = $gift->name;
            $ar['quantity']       = $gift->quantity;
            $ar['original_image'] = self::getImgPathByImgUrl($gift->original_image);
            $ar['thumbnail']      = self::getImgPathByImgUrl($gift->thumbnail);
            $ar['created_at']     = time();

            SQL::insert(['table'  => 'order_gifts',
                         'insert' => $ar]);
        }
        return 'M00000';
    }

    /**
        记录订单详情
     */
    function insert_order_details($good,$arr,$type = 1){

        /*
            减库存
            1.模版库存 — √
            3.素材库存 — x
            4.商品库存 — √
         */
        $temp = $this->tempDecrementStock((isset($good->product_temp_id) ? $good->product_temp_id : ''),
                                          (isset($good->colour_name) ? $good->colour_name : ''),
                                          (isset($good->size_name) ? $good->size_name : ''),
                                          intval($good->quantity));

        if(!$temp) return 'M05016';
        if($type == 1){
            $can_buy = $this->can_order($good->product_id, $good->colour_name, $good->size_name, $good->quantity, $good->user_id . '');
            if($can_buy['state'] != 'M00000') return $can_buy;
        }else if($type == 2){
            $can_buy = ProductTempTool::getProductTempAcualStock($good->product_temp_id,
                                                                 $good->colour_name,
                                                                 $good->size_name);

            if($can_buy < $good->quantity) return ['state' => 'M08012',
                                                   'message' => '库存不足产品编号' . $good->product_id .
                                                                ' 颜色:' . $good->colour_name .
                                                                ' 尺码:' . $good->size_name.
                                                                '商品库存剩余' . $can_buy .'件'];
        }


        //$gift = $this->
        $prod = $this->product_stock_change((isset($good->product_id) ? $good->product_id : ''),
                                            (isset($good->quantity) ? intval($good->quantity) : 0),
                                            2);
        if(!$prod) return GeneralTool::createResult('','M05016');

        //删除购物车
        $this->carTool->shop_car_clean(['shop_car_id' => $good->shop_car_id]);

        $ar['order_id']           = $arr['order_id'];
        $ar['product_id']         = $good->product_id;
        $ar['product_user_id']    = $good->user_id . '';
        $ar['product_temp_name']  = $good->product_temp_name;
        $ar['brand_name']         = $good->brand_name;
        $ar['brand_id']           = $good->brand_id;
        $ar['quantity']           = $good->quantity;
        $ar['colour_name']        = $good->colour_name;
        $ar['size_name']          = $good->size_name;
        $ar['overflow_price']     = $good->overflow_price;
        $ar['original_price']     = $good->original_price;
        $ar['preferential_price'] = $good->preferential_price;
        $ar['postage']            = isset($good->product_temp->postage)? $good->product_temp->postage : 0;
        $ar['thumbnail']          = isset($good->thumbnail[0]) ? ImgTool::getImgPathByImgUrl($good->thumbnail[0]) : '';
        $ar['original_image']     = isset($good->original_image[0]) ? ImgTool::getImgPathByImgUrl($good->original_image[0]) : '';
        $ar['created_at']         = time();
        $ar['updated_at']         = $ar['created_at'];

        $result = SQL::insert(['table'  => 'order_details',
                               'insert' => $ar]);
        return GeneralTool::createResult('',($result ? 'M00000' : 'M05015'));
    }

    /**
        记录收货地址
     */
    function insert_order_express($arr,$address){
        $ar['order_id'] = $arr['order_id'];

        if(!isset($address['result']->consignee) || trim($address['result']->consignee) == '') return 'M05009';
        $ar['consignee'] = $address['result']->consignee;

        if(!isset($address['result']->phone) || trim($address['result']->phone) == '') return 'M05010';
        $ar['phone'] = $address['result']->phone;

        if(!isset($address['result']->city) || trim($address['result']->city) == '') return 'M05012';
        if(!isset($address['result']->address) || trim($address['result']->address) == '') return 'M05013';

        $ar['address']          = $address['result']->city . ' ' . $address['result']->address;
        $ar['order_express_id'] = '';
        $ar['express_name']     = '';
        $ar['express_id']       = '';
        $ar['created_at']       = time();
        $ar['updated_at']       = $ar['created_at'];

        $order_express = SQL::insert(['table'=>'order_express',
                                      'insert'=>$ar]);
        return $order_express ? 'M00000' : 'M05014';
    }

    /**
        记录优惠券
        return 1成功 0失败
     */
    function insert_order_coupons($arr,$coupon){
        if(!isset($coupon['discount']) || !is_numeric($coupon['discount'])) return 1;
        if(!isset($coupon['coupon_price']) || !is_numeric($coupon['coupon_price'])) return 0;

        $ar['using_time'] = time();
        $ar['updated_at'] = $ar['using_time'];
        $use = SQL::update(['table'  => 'coupons',
                            'where'  => ['coupon_id'  =>$coupon['coupon_id'],
                                         'using_time' =>0,
                                         'state'      =>1],
                            'update' => $ar]);
        if(!$use) return 0;

        $insert['coupon_id']    = $coupon['coupon_id'];
        $insert['order_id']     = $arr['order_id'];
        $insert['type']         = $coupon['type'];
        $insert['resource_id']  = $coupon['reg_id'];
        $insert['real_price']   = $coupon['discount'];
        $insert['coupon_price'] = $coupon['coupon_price'];
        $insert['created_at']   = time();
        $insert['updated_at']   = $insert['created_at'];

        $order_coupon = SQL::insert(['table' => 'order_coupons',
                                     'insert' => $insert]);
        return $order_coupon;

    }

    /**
        更新订单平台归属
     */
    function update_order_platform($input){
        $input['platform'] = $this->order_platform($input['platform']);
        $result = SQL::update(['table'  => 'orders',
                               'where'  => ['order_id' => $input['order_id'],
                                            'buyer_id'  => $input['user_id']],
                               'update' => ['platform' =>$input['platform']]]);
        return $result;
    }


    /**
        工具
     */
    //订单平台
    function order_platform($input){
        switch($input){
            case 'IOS':
            case 'Android':
            case 'Web':
                return $input;
            default:
                return 'IOS';
        }
    }
    //订单资费明细类型
    function order_detail_fee_type($input){
        switch($input){
            case 1:
                //自定义素材
                return 2;
            case 2:
                //系统素材
                return 3;
            case 3:
                //字体
                return 4;
            default:
                return 0;
        }
    }

    /**
        支付
     */

    /**
        获取订单支付信息
     */
    function get_order_pay_info($input){
        $total_fee = SQL::pluck(['table'=>'orders',
                                 'where'=>['buyer_id'     => $input['user_id'],
                                           'order_id'     => $input['order_id'],
                                           'pay_state'    => 0,
                                           'pay_type'     => 0,
                                           'type'         => 'order',
                                           'is_cancel'    => 0,
                                           'is_aftermark' => 0,
                                           'state'        => 1],
                                 'pluck'=>'total_fee']);
        if(!isset($total_fee)) return ['state'=>'M05019'];
        if($total_fee < 0) return ['state'=>'M05018'];
        if($total_fee == 0 && $this->get_order_coupon_count(['order_id'=>$input['order_id'],'state'=>1]) == 0)
            return ['state'=>'M05019'];
        if($total_fee == 0) return ['state'=>'M05020'];
        return ['state'=>'M00000','data'=>['total_fee'=>$total_fee]];
    }

    /**
        判断订单是否使用优惠券
     */
    function get_order_coupon_count($input){
        $result = SQL::count(['table' => 'order_coupons',
                              'where'=>$input]);
        return $result;
    }

    /**
        订单支付成功操作
        type 1微信 2支付宝 3优惠券
     */
    function order_pay_success($input,$type = 1){
        $input     = $this->get_input_by_pay_success($input, $type);
        //修改订单状态
        $order     = $this->update_order_by_pay_success($input);
        //添加操作记录
        $operation = $this->order_operation_by_pay_success($input);
        //添加已售
        $sale      = $this->order_sale_synchronization($input);
        //活动订单同步
        $sync      = self::order_sync_active($input);
        //推送
        $push      = $this->pay_order_success_push($input);
        //发送邮件
        $eamil     = $this->order_email_by_pay_success($input);

        return true;
    }

    static function order_sync_active($input){
        $order   = DB::table('orders')
                   ->where(['order_id'     => $input['order_id'],
                            'pay_state'    => 0,
                            'pay_type'     => 0,
                            // 'total_fee'    => $input['total_fee'],
                            'type'         => 'order',
                            'state'        => 1,
                            'is_cancel'    => 0,
                            'is_aftermark' => 0])
                   ->where('channel_id', '<>', '')
                   ->first();
        if(!isset($order)) return false;
        $data['order_id'] = $input['order_id'];
        $data['user_id']  = $order->buyer_id;
        $str = GeneralTool::createLinkstring($data);
        switch($order->channel_id){
            case 'kanjia20170310':
                $url = env('WEI_SHOP_URL') . 'change-order-state';
                break;
            case 'septwolves20170316':
                $url = env('WEI_SHOP_URL') . 'septwolves-change-order-state';
                break;
            default:
                $url = env('WEI_SHOP_URL') . 'change-order-state';
        }
        $result = GeneralTool::http_curl($url, $str, 1);
        return $result;
    }

    /**
        发送下单邮件
     */
    function order_email_by_pay_success($input){
        $rex = SQL::first(['table' => 'order_express',
                           'where' => ['order_id' => $input['order_id'],
                                       'state'    => 1]]);
        $total_fee = SQL::pluck(['table' => 'orders',
                                 'where' => ['order_id' => $input['order_id']],
                                 'pluck' => 'total_fee']);
        self::SendToMail(['reg_id'    => $input['order_id'],
                           'type'      => 'order_pay',
                           'rece_user' => env('REMIND_RECE_EMAIL'),
                           'full_name' => isset($rex->consignee)?$rex->consignee:'',
                           'tel'       => isset($rex->phone)?$rex->phone:'',
                           'message'   => '买家下单']);
        self::push_wx(['title'     => '您好，有一条新的订单',
                        'body'      => '详见后台订单详情页面',
                        'total_fee' => (isset($total_fee) ? $total_fee : ''),
                        'name'      => isset($rex->consignee) ? $rex->consignee : '',
                        'phone'     => isset($rex->phone) ? $rex->phone : '',
                        'order_id'  => isset($input['order_id']) ? $input['order_id'] : '']);
        return true;
    }

    /**
        添加订单商品售量
     */
    function order_sale_synchronization($input){
        /**
            素材已售 +
            商品已售 +
            认证用户销量 +
         */
        //素材
        $source = $this->order_source_sale_num_up($input);
        //商品 认证用户销量
        $product = $this->order_product_sale_num_up($input);
    }

    /**
        添加商品销量
     */
    function order_product_sale_num_up($input){
        $details = $this->get_order_detail(['order_id' => $input['order_id'],
                                            'state'    => 1]);
        foreach($details as $detail){
            $this->product_sell_num($detail->product_id, $detail->quantity);
            $this->addSellNum($detail->product_user_id, $detail->quantity);
        }
        return true;
    }

    /**
        添加素材已售
     */
    function order_source_sale_num_up($input){
        $details = $this->get_order_detail_fee(['order_id' => $input['order_id'],
                                                'type'     => [2,3],
                                                'state'    => 1]);
        foreach($details as $detail){
            $this->updateSourcePicUsedNum($detail->resource_id, $detail->quantity);
        }
        return true;
    }

    /**
        添加订单支付成功记录
     */
    function order_operation_by_pay_success($input){
        $arr['order_id'] = $input['order_id'];
        $arr['user_id']  = $this->get_user_id_by_order_id($arr['order_id']);
        $arr['iden']     = 1;
        $arr['order_state'] = 1;
        $arr['over_order_state'] = 2;

        $operation = self::insert_order_operation($arr);
        return $operation;
    }

    /**
        修改订单状态
     */
    function update_order_by_pay_success($input){
        $update = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $input['order_id'],
                                           'pay_state'    => 0,
                                           'pay_type'     => 0,
                                           // 'total_fee'    => $input['total_fee'],
                                           'type'         => 'order',
                                           'state'        => 1,
                                           'is_cancel'    => 0,
                                           'is_aftermark' => 0],
                               'update' => ['pay_state'  => 2,
                                            'pay_type'   => $input['type'],
                                            'trade_no'   => $input['trade_no'],
                                            'state'      => 2,
                                            'updated_at' => time()]]);
        return $update;
    }

    //记录取消原因
    static function save_reason_from_cancel($input){
        $result = SQL::update(['table' => 'orders',
                               'where' => ['order_id'        => $input['order_id']],
                               'update'=> ['cancel_reason'   => $input['reason']]]);
        return $result;
    }


    /**
        工具
     */
    /**
        订单编号获取优惠券编号
     */
    function get_coupon_id_by_order_id($order_id){
        $coupon_id = SQL::pluck(['table' => 'order_coupons',
                                 'where' => ['order_id' => $order_id,
                                             'state'    => 1],
                                 'pluck' => 'coupon_id']);
        return $coupon_id;
    }
    /**
        获取订单详情数据
     */
    function get_order_detail($input){
        $result = SQL::get(['table' => 'order_details',
                            'where' => $input]);
        return $result;
    }
    /**
        获取订单资费明细数据
     */
    function get_order_detail_fee($input){
        $result = DB::table('order_detail_fees')
                  ->where(['order_id' => $input['order_id'],
                           'state'    => $input['state']])
                  ->whereIn('type',$input['type'])
                  ->get();
        return $result;
    }
    /**
        订单编号获取买家编号
     */
    function get_user_id_by_order_id($input){
        $user_id = SQL::pluck(['table' => 'orders',
                               'where' => ['order_id' => $input],
                               'pluck' => 'buyer_id']);
        return isset($user_id) ? $user_id : '';
    }
    /**
        添加操作记录
     */
    static function insert_order_operation($arr){
        $arr['created_at'] = time();
        $insert = SQL::insert(['table'  => 'order_operations',
                               'insert' => $arr]);
        return $insert;
    }
    /**
        获取支付成功数据
     */
    function get_input_by_pay_success($input, $type){
        switch($type){
            case 1:
                //微信
                $input['order_id']  = substr($input['out_trade_no'],0,-5);
                $input['trade_no']  = $input['transaction_id'];
                $input['total_fee'] = floatval($input['total_fee']/100);
                $input['type']      = 1;

                return $input;
            case 2:
                //支付宝
                $input['order_id']  = $input['out_trade_no'];
                $input['trade_no']  = $input['trade_no'];
                $input['total_fee'] = isset($input['buyer_pay_amount']) ? $input['buyer_pay_amount'] : $input['total_fee'];
                $input['type']      = 2;

                return $input;
            case 3:
                //优惠券
                $input['type']      = 3;
                $input['trade_no']  = $this->get_coupon_id_by_order_id($input['order_id']);
                return $input;
            default:
                return $input;
        }
    }
    /**
        邮件
     */
    static function SendToMail($input){
        //$email    = "547274138@qq.com";
        $username = "";
        $to = explode(',',$input['rece_user']);
        Log::info($to);
        foreach($to as $email){
            Log::info($email);

            try{
                $data = ['email'     => $email,
                         'full_name' => $input['full_name'],
                         'order_id'  => $input['reg_id'],
                         'tel'       => $input['tel'],
                         'username'  => $username,
                         'messages'  => $input['message']];
                //dd($data);
                Mail::send('activemail', $data, function ($message) use ($data) {
                    $message->to($data['email'], $data['username'])->subject($data['messages']);
                });
                $result = SQL::insert(['table'=>'email_records',
                                       'insert'=>array('reg_id'     => $input['reg_id'],
                                                       'type'       => $input['type'],
                                                       'message'    => $input['message'],
                                                       'rece_user'  => $email,
                                                       'created_at' => time())]);


            }catch(\Exception $e){
                Log::info($e);
            }
        }
        return true;
    }


    /**
        订单列表
     */

    /**
        订单列表
     */
    function get_order_list($input,$arr){
        $orders = DB::table('orders')
                  ->where($arr['where'])
                  ->whereIn('state',$arr['state'])
                  ->orderBy($arr['order'],$arr['sort'])
                  ->select('order_id',
                           'buyer_id',
                           'total_postage',
                           'total_fee',
                           'state',
                           'is_cancel',
                           'is_aftermark',
                           'worksheet_id',
                           'enabled_worksheet',
                           'is_close')
                  ->paginate($input['per_page'])
                  ->toArray();
        $orders['total_page'] = $orders['last_page'];

        foreach($orders['data'] as $order){
            $order->total_fee           = GeneralTool::priceFormat($order->total_fee).'';
            $order->total_postage       = GeneralTool::priceFormat($order->total_postage).'';
            $order->state_str           = $this->get_order_state_str($order);
            $order->after_str           = $order->state == 4 && $order->is_aftermark ? '售后处理中' : '';
            $order->can_aftermark       = $this->order_can_aftermark($order);
            $order->order_after_id      = $order->is_aftermark ? $this->get_order_after_id_now($order->order_id) : '';
            $goods                      = $this->get_order_detail_goods_from_list($order->order_id);
            $order->good_total_quantity = $goods['good_total_quantity'];
            $order->total_price         = GeneralTool::priceFormat($goods['total_price']).'';
            $order->goods               = ['vaild' => $goods['vaild']];
        }
        return $orders;
    }

    /**
        获取订单是否可申请售后
     */
    function order_can_aftermark($order){
        if($order->state == 4 && $order->is_cancel == 0 && $order->is_aftermark == 0 && $order->is_close == 0){
            $operation = SQL::first(['table' => 'order_operations',
                                     'where' => ['order_id'         => $order->order_id,
                                                 'over_order_state' => 4]]);
            if(!isset($operation) || !isset($operation->created_at) || $operation->created_at == 0) return 0;

            $after_vaild_time = self::get_data_from_configs(['name' => 'order_after','state' => 1]);

            if(!isset($after_vaild_time) || $after_vaild_time == 0) return 0;

            return (time() - $operation->created_at < $after_vaild_time)? 1 : 0;
        }
        return 0;
    }

    /**
        获取订单详情页参数
     */
    function get_data_from_detail_page($input){
        $data  = $this->get_order_info_from_table_orders(['order_id' => $input['order_id'],
                                                          'buyer_id' => $input['user_id']]);

        if(!isset($data->state) || $data->state == 0) return (object)[];

        $order = (object)[];

        $order->order_id            = isset($data->order_id) ? $data->order_id : '';
        $order->buyer_id            = isset($data->buyer_id) ? $data->buyer_id : '';
        $order->worksheet_id        = isset($data->worksheet_id) ? $data->worksheet_id : '';
        $order->enabled_worksheet   = isset($data->enabled_worksheet) ? $data->enabled_worksheet : 0;
        $order->total_postage       = isset($data->total_postage) ? GeneralTool::priceFormat($data->total_postage).'' : '';
        $order->total_fee           = isset($data->total_fee) ? GeneralTool::priceFormat($data->total_fee).'' : '';
        $order->state               = isset($data->state) ? $data->state : '';
        $order->is_cancel           = isset($data->is_cancel) ? $data->is_cancel : 0;
        $order->is_aftermark        = isset($data->is_aftermark) ? $data->is_aftermark : 0;
        $order->order_after_id      = $order->is_aftermark ? $this->get_order_after_id_now($order->order_id) : '';
        $order->state_str           = $this->get_order_state_str($order);
        $order->after_str           = $order->state == 4 && $order->is_aftermark ? '售后处理中' : '';
        $order->is_close            = isset($data->is_close) ? $data->is_close : 0;
        $order->can_aftermark       = $this->order_can_aftermark($order);
        $goods                      = $this->get_order_detail_goods_from_list($order->order_id,2);
        $order->good_total_quantity = $goods['good_total_quantity'];
        $order->total_price         = GeneralTool::priceFormat($goods['total_price']) . '';
        $order->discount_price      = isset($data->channel_id) && $data->channel_id != '' ?
                                      ($order->total_price - $order->total_fee) . '' : $this->get_order_discount_price($order->order_id) . '';

        $order->created_at_str      = isset($data->created_at) ? date('Y-m-d H:i:s',$data->created_at) : '';
        $order->pay_time_str        = $this->get_order_operation_time($order->order_id,'pay');
        $order->send_time_str       = $this->get_order_operation_time($order->order_id,'send');
        $order->sign_time_str       = $this->get_order_operation_time($order->order_id,'sign');
        $order->cancel_time_str     = $this->get_order_operation_time($order->order_id,'cancel');
        $order->created_at          = isset($data->created_at) ? $data->created_at : 0;
        $title_data                 = $this->get_order_title_message_time($order);
        $order->title               = isset($title_data['title']) ? $title_data['title'] : '';
        $order->title_message       = isset($title_data['message']) ? $title_data['message'] : '';
        $order->residual_time       = isset($title_data['time'])? $title_data['time'] : 0;

        $order->receiving           = $this->get_order_receiving($order->order_id);
        $order->goods               = ['vaild' => $goods['vaild'],'unvaild'=>[]];
        return $order;
    }

    /**
        取消订单 type 1用户 2运营
     */
    static function order_cancel($input, $type = 1){
        if($type == 1){
            $result = SQL::update(['table' => 'orders',
                                   'where' => ['order_id'     => $input['order_id'],
                                               'buyer_id'     => $input['user_id'],
                                               'state'        => 1,
                                               'is_cancel'    => 0,
                                               'is_aftermark' => 0],
                                   'update'=> ['is_cancel'  => 1,
                                               'is_close'   => 1,
                                               'updated_at' => time()]]);

            if(!$result) return 'M05023';

            $operation = self::insert_order_operation(['order_id'         => $input['order_id'],
                                                        'iden'             => (isset($input['iden']) && $input['iden'] == 0 ? 0 : 1),
                                                        'user_id'          => (isset($input['iden']) && $input['iden'] == 0 ? '0' :$input['user_id']),
                                                        'order_state'      => 1,
                                                        'over_order_state' => 1,
                                                        'is_cancel'        => 1,
                                                        'is_close'         => 1]);
        }else{
            $result = SQL::update(['table' => 'orders',
                                   'where' => ['order_id'     => $input['order_id'],
                                               'state'        => 2,
                                               'is_cancel'    => 0,
                                               'is_aftermark' => 0],
                                   'update'=> ['is_cancel'  => 1,
                                               'is_close'   => 1,
                                               'updated_at' => time()]]);


            $operation = self::insert_order_operation(['order_id'         => $input['order_id'],
                                                        'iden'             => 2,
                                                        'user_id'          => (isset($input['iden']) && $input['iden'] == 0 ? '0' :$input['user_id']),
                                                        'order_state'      => 2,
                                                        'over_order_state' => 2,
                                                        'is_cancel'        => 1,
                                                        'is_close'         => 1,
                                                        'need_refund'      => 1,
                                                        'is_refund'        => 1]);
            self::cancel_order_success_push_backstage($input);
        }


        //优惠券
        self::coupon_return_from_order_cancel($input);
        //加库存！！！！
        self::good_stock_return($input);

        return 'M00000';
    }

    /**
        申请售后
     */
    function order_submit_aftermark($input){
        $result = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $input['order_id'],
                                           'buyer_id'     => $input['user_id'],
                                           'state'        => 4,
                                           'is_cancel'    => 0,
                                           'is_aftermark' => 0],
                               'update'=> ['is_aftermark' => 1,
                                           'updated_at' => time()]]);

        if(!$result) return 'M05031';

        $operation = self::insert_order_operation([ 'order_id'         => $input['order_id'],
                                                    'iden'             => 1,
                                                    'user_id'          => $input['user_id'],
                                                    'order_state'      => 4,
                                                    'over_order_state' => 4,
                                                    'is_aftermark'     => 1,
                                                    'order_after_id'   => $input['order_after_id'],
                                                    'after_state'      => 1,
                                                    'over_after_state' => 1]);

        return 'M00000';
    }

    /**
        获取订单物流信息
     */
    function get_order_expree_info($input){
        $express = SQL::first(['table' => 'order_express',
                               'where' => ['order_id' => $input]]);
        return isset($express) ? $express : (object)[];
    }

    /**
        确认收货
     */
    static function order_sign($input){

        $result = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $input['order_id'],
                                           'buyer_id'     => $input['user_id'],
                                           'state'        => 3,
                                           'is_cancel'    => 0,
                                           'is_aftermark' => 0],
                               'update'=> ['state'      => 4,
                                           'updated_at' => time()]]);

        if(!$result) return 'M05024';

        $operation = self::insert_order_operation([ 'order_id'         => $input['order_id'],
                                                    'iden'             => (isset($input['iden']) && $input['iden'] == 0 ? 0 : 1),
                                                    'user_id'          => (isset($input['iden']) && $input['iden'] == 0 ? '0' : $input['user_id']),
                                                    'order_state'      => 3,
                                                    'over_order_state' => 4]);

        return 'M00000';
    }

    /**
        删除订单
     */
    function order_delete($input, $complete, $is_cancel){

        if($complete){
            $result = SQL::update(['table' => 'orders',
                                   'where' => ['order_id'     => $input['order_id'],
                                               'buyer_id'     => $input['user_id'],
                                               'state'        => 4,
                                               'is_cancel'    => 0,
                                               'is_aftermark' => 0],
                                   'update'=> ['state'      => 0,
                                               'updated_at' => time()]]);

            if(!$result) return 'M00001';

            $operation = self::insert_order_operation([ 'order_id'         => $input['order_id'],
                                                        'iden'             => 1,
                                                        'user_id'          => $input['user_id'],
                                                        'order_state'      => 4,
                                                        'over_order_state' => 0]);

            return 'M00000';
        }else if($is_cancel){
            $result = SQL::update(['table' => 'orders',
                                   'where' => ['order_id'     => $input['order_id'],
                                               'buyer_id'     => $input['user_id'],
                                               'state'        => 1,
                                               'is_cancel'    => 1],
                                   'update'=> ['state'      => 0,
                                               'updated_at' => time()]]);

            if(!$result) return 'M00001';

            $operation = self::insert_order_operation(['order_id'         => $input['order_id'],
                                                        'iden'             => 1,
                                                        'user_id'          => $input['user_id'],
                                                        'order_state'      => 1,
                                                        'over_order_state' => 0]);

            return 'M00000';
        }
        return 'M05039';
    }

    /**
        关闭订单
     */
    static function order_close($order){
        $result = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $order->order_id,
                                           'is_close'     => 0],
                               'update'=> ['is_close'   => 1,
                                           'updated_at' => time()]]);

        if(!$result) return 'M00001';

        $operation = self::insert_order_operation(['order_id'         => $order->order_id,
                                                   'iden'             => 0,
                                                   'user_id'          => '0',
                                                   'is_close'         => 1,
                                                   'order_state'      => $order->state,
                                                   'over_order_state' => $order->state]);
        return 'M00000';
    }

    /**
        发货
     */
    function order_send_goods($order){
        $result = SQL::update(['table' => 'orders',
                               'where' => ['order_id'     => $order->order_id,
                                           'state'        => 2,
                                           'send_state'   => 0],
                               'update'=> ['state'      => 3,
                                           'send_state' => 1,
                                           'updated_at' => time()]]);

        if(!$result) return 'M00001';

        $operation = self::insert_order_operation(['order_id'         => $order->order_id,
                                                   'iden'             => 0,
                                                   'user_id'          => Auth::user()->id,
                                                   'order_state'      => 2,
                                                   'over_order_state' => 3]);
        return 'M00000';
    }

    /**
        工具
     */

    /**
        金额分配
     */
    static function deal_with_by_order_detail_fee($input){
        $fees = DB::table('order_detail_fees')
                ->where(['order_id' => $input['order_id'],
                         'is_deal'  => 0,
                         'state'    => 1])
                ->whereIn('type', [3,5])
                ->select('order_detail_fee_number', 'user_id', 'type', 'resource_id', 'thumbnail', 'preferential_price', 'quantity')
                ->get();
        foreach($fees as $fee){
            if($fee->preferential_price <= 0 || $fee->quantity <= 0) continue;
            $result = IncomeTool::add_user_balance_change($fee);
            if(!$result) Throw new \Exception('余额修改失败');
            SQL::update(['table' => 'order_detail_fees',
                         'where' => ['order_detail_fee_number' => $fee->order_detail_fee_number],
                         'update'=> ['is_deal' => 1]]);
        }
        return 'M00000';
    }

    /**
        商品库存归还
     */
    static function good_stock_return($input){
        $details = SQL::get(['table' => 'order_details',
                             'where' => ['order_id' => $input['order_id'],
                                         'state'    => 1]]);
        foreach($details as $det){
            /*
                归还数据：
                    1.商品 √
                    2.产品模版√
                    3.赠品 √
             */
            self::product_stock_change($det->product_id, $det->quantity, 1);
            $fee = SQL::first(['table' => 'order_detail_fees',
                               'where' => ['order_id'   => $input['order_id'],
                                           'product_id' => $det->product_id,
                                           'type'       => 1]]);
            // if(isset($fee->resource_id)) self::tempIncrementStock($fee->resource_id, $det->colour_name, $det->size_name, intval($det->quantity));
        }
        $gifts = self::get_order_gifts(['order_id' => $input['order_id'],
                                         'state'    => 1]);
        Log::info($gifts);
        foreach($gifts as $gift){
            self::giftIncrementStock($gift->gift_id, $gift->quantity);
        }
    }
    /**
        优惠券归还
     */
    static function coupon_return_from_order_cancel($input){
        $coupon_id = SQL::pluck(['table' => 'order_coupons',
                                 'where' => ['order_id' => $input['order_id'],
                                             'state'    => 1],
                                 'pluck' => 'coupon_id']);
        if(!isset($coupon_id)) return true;

        $update = SQL::update(['table' => 'coupons',
                               'where' => ['coupon_id' => $coupon_id],
                               'update'=> ['using_time' => 0]]);
        return $update;
    }
    static function get_order_gifts($input){
        $gifts = SQL::get(['table' => 'order_gifts',
                           'where' => $input]);
        return $gifts;
    }
    /**
        获取订单商品数量
     */
    function get_order_good_total_quantity($input){
        $lists = SQL::lists(['table' => 'order_details',
                             'where' => ['order_id' => $input,
                                         'state'    => 1],
                             'lists' => 'quantity']);
        return array_sum($lists);
    }
    /**
        获取订单商品第一件作品图片
     */
    static function get_order_first_picture($input){
        $detail = SQL::first(['table' => 'order_details',
                              'where' => ['order_id' => $input,
                                          'state'    => 1]]);
        $arr['thumbnail'][0]      = isset($detail->thumbnail) ? env('IMG_URL_STD_PREFIX') . $detail->thumbnail : '';
        $arr['original_image'][0] = isset($detail->original_image) ? env('IMG_URL_STD_PREFIX') . $detail->original_image : '';
        return $arr;
    }
    /**
        判断订单是否存在
     */
    function get_order_count($input){
        $count = SQL::count(['table' => 'orders',
                             'where' => $input]);
        return $count;
    }
    /**
        获取订单状态标题
     */
    function get_order_title_message_time($order){
        if($order->is_cancel){
            $arr['title']   = '订单已取消';
            $arr['message'] = $this->get_order_operation_time($order->order_id,'cancel');
            $arr['time']    = 0;
            return $arr;
        }

        switch($order->state){
            case 1:
                $arr['title']   = '订单还未付款';
                $long           = self::get_data_from_configs(['name' => 'order_unpay']);
                $long           = !isset($long) || !is_numeric($long)? 0 : $long;
                $arr['time']    = $order->created_at + $long - time();
                $arr['time']    = $arr['time'] < 0 ? 0 : $arr['time'];
                $arr['message'] = GeneralTool::residualTimeFormat($arr['time']) . '后订单自动取消';
                return $arr;
            case 2:
                $arr['title']   = '卖家还未发货';
                $arr['message'] = '可催卖家及时发货';
                $arr['time']    = 0;
                return $arr;
            case 3:
                $arr['title']   = '卖家已发货';
                $long           = self::get_data_from_configs(['name' => 'order_unsign']);
                $long           = !isset($long) || !is_numeric($long)? 0 : $long;
                $send_time      = strtotime($order->send_time_str) ? strtotime($order->send_time_str) : 0;
                if($long != 0 && $send_time != 0){
                    $arr['time']= $send_time + $long - time();
                    $arr['time']= $arr['time'] < 0 ? 0 : $arr['time'];
                }else{
                    $arr['time']= 0;
                }

                $arr['message'] = GeneralTool::residualTimeFormat($arr['time']) . '后自动确认收货';
                return $arr;
            case 4:
                $arr['title']   = '订单已完成';
                $long           = self::get_data_from_configs(['name' => 'order_after']);
                $long           = !isset($long) || !is_numeric($long)? 0 : $long;
                $sign_time      = strtotime($order->sign_time_str) ? strtotime($order->sign_time_str) : 0;
                if($long != 0 && $sign_time != 0){
                    $arr['time']= $sign_time + $long - time();
                    $arr['time']= $arr['time'] < 0 ? 0 : $arr['time'];
                }else{
                    $arr['time']= 0;
                }

                $arr['message'] = GeneralTool::residualTimeFormat($arr['time']) . '后停止退换货';
                return $arr;
            default:
                return '';
        }
    }
    /**
        获取订单操作时间字符串
     */
    function get_order_operation_time($order_id,$type,$time_type = 'format'){
        $input = [];

        switch($type){
            case 'pay':
                $input['order_id']         = $order_id;
                $input['order_state']      = 1;
                $input['over_order_state'] = 2;
                break;
            case 'send':
                $input['order_id']         = $order_id;
                $input['order_state']      = 2;
                $input['over_order_state'] = 3;
                break;
            case 'sign':
                $input['order_id']         = $order_id;
                $input['order_state']      = 3;
                $input['over_order_state'] = 4;
                break;
            case 'cancel':
                $input['order_id']         = $order_id;
                $input['is_cancel']        = 1;
                break;
            case 'after_fail':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 1;
                $input['over_after_state'] = 0;
                break;
            case 'after_pass':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 1;
                $input['over_after_state'] = 2;
                break;
            case 'after_user_send_back':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 2;
                $input['over_after_state'] = 3;
                break;
            case 'after_backstage_sign':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 3;
                $input['over_after_state'] = 4;
                break;
            case 'after_backstage_in_process':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 4;
                $input['over_after_state'] = 5;
                break;
            case 'after_backstage_send_back':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 5;
                $input['over_after_state'] = 6;
                break;
            case 'after_user_sign':
                $input['order_after_id']   = $order_id;
                $input['after_state']      = 6;
                $input['over_after_state'] = 7;
                break;
        }

        $operation = DB::table('order_operations')
                     ->where($input)
                     ->first();
        if(isset($operation->created_at) && $time_type == 'format'){
            return date('Y-m-d H:i:s',$operation->created_at);
        }else if(isset($operation->created_at)){
            return $operation->created_at;
        }
        return '';
    }
    /**
        获取订单收货信息
     */
    function get_order_receiving($order_id, $type = 1){
        $rece = SQL::first(['table' => 'order_express',
                            'where' => ['order_id' => $order_id,
                                        'state'    => 1]]);
        if(!isset($rece)) return (object)[];

        $object            = (object)[];
        $object->consignee = isset($rece->consignee) ? $rece->consignee : '';
        $object->phone     = isset($rece->phone) ? $rece->phone : '';
        $object->address   = isset($rece->address) ? $rece->address : '';
        if($type = 2){
            $object->express_id       = isset($rece->express_id) ? $rece->express_id : '';
            $object->express_name     = isset($rece->express_name) ? $rece->express_name : '';
            $object->order_express_id = isset($rece->order_express_id) ? $rece->order_express_id : '';
        }
        return $object;
    }
    /**
        获取订单优惠金额
     */
    function get_order_discount_price($order_id){
        $discount_price = SQL::pluck(['table' => 'order_coupons',
                                      'where' => ['order_id' => $order_id,
                                                  'state'    => 1],
                                      'pluck' => 'real_price']);
        return isset($discount_price) ? GeneralTool::priceFormat($discount_price).'' : '0';
    }
    /**
        获取订单主表数据
     */
    function get_order_info_from_table_orders($input){
        $order = SQL::first(['table' => 'orders',
                             'where' => $input]);
        return $order;
    }
    /**
        获取配置sql信息
     */
    static function get_data_from_configs($input){
        $data = SQL::pluck(['table' => 'configs',
                            'where' => $input,
                            'pluck' => 'value']);
        return $data;
    }
    /**
        获取订单状态字符串
     */
    function get_order_state_str($order){
        if($order->is_cancel) return '已取消订单';

        switch($order->state){
            case 1:
                return '待付款订单';
            case 2:
                return '待发货订单';
            case 3:
                return '待收货订单';
            case 4:
                return '已完成订单';
            default:
                return '';
        }
    }
    /**
        获取订单列表商品
     */
    function get_order_detail_goods_from_list($order_id, $type = 1){
        $goods['good_total_quantity'] = 0;
        $goods['total_price'] = 0;
        $details = $this->get_order_detail(['order_id' => $order_id,
                                            'state'    => 1]);
        $goods['vaild'] = [];
        foreach($details as $detail){
            $arr                        = [];
            $arr['order_detail_number'] = isset($detail->order_detail_number) ? $detail->order_detail_number . '' : '';
            $arr['product_id']          = isset($detail->product_id) ? $detail->product_id : '';
            $arr['product_temp_name']   = isset($detail->product_temp_name) ? $detail->product_temp_name : '';
            $arr['brand_name']          = isset($detail->brand_name) ? $detail->brand_name : '';
            $arr['quantity']            = isset($detail->quantity) ? $detail->quantity : 0;
            $arr['colour_name']         = isset($detail->colour_name) ? $detail->colour_name : '';
            $arr['size_name']           = isset($detail->size_name) ? $detail->size_name : '';
            $arr['original_price']      = isset($detail->original_price) ? GeneralTool::priceFormat($detail->original_price).'' : 0;
            $arr['preferential_price']  = isset($detail->preferential_price) ? GeneralTool::priceFormat($detail->preferential_price).'' : 0;
            $arr['has_preferential']    = $arr['original_price'] != $arr['preferential_price'] ? 1 : 0;
            $arr['thumbnail'][0]        = isset($detail->thumbnail) ? env('IMG_URL_STD_PREFIX') . $detail->thumbnail : '';
            $arr['original_image'][0]   = isset($detail->original_image) ?
                                          env('IMG_URL_STD_PREFIX') . $detail->original_image : '';
            $arr['gift']                = $this->get_order_product_gift($arr,$order_id);
            foreach($arr['gift'] as $gift){
                $goods['good_total_quantity'] += (isset($gift->quantity) ? $gift->quantity : 0);
            }
            if($type == 2){
                $arr['lists'] = $this->get_order_product_fee_lists($arr, $order_id);
            }else if($type == 3){
                $arr['lists']       = $this->get_order_product_fee_lists($arr, $order_id, 2);
                $arr['print_state'] = isset($detail->print_state) ? $detail->print_state : 0;
            }else{
                $arr['lists'] = [];
            }

            $goods['vaild'][]             = (object)$arr;
            $goods['good_total_quantity'] += $arr['quantity'];
            $goods['total_price']         += $arr['preferential_price'] * $arr['quantity'];
        }
        return $goods;
    }

    /**
        获取打印图对象
     */
    function get_order_product_prints($detail, $order_id){
        $prints = SQL::get(['table' => 'order_detail_prints',
                            'where' => ['order_id'   => $order_id,
                                        'product_id' => $detail->product_id]]);

        $arr = [];
        foreach($prints as $print){
            $image = $this->get_product_preview_images_by_id($print->print_picture_id);//dd($image);
            $ar['type']                 = isset($image->craftsmanship_name) ? $image->craftsmanship_name : '';
            $ar['thumbnail']            = isset($image->product_preview_thumbnail_image) ? $image->product_preview_thumbnail_image : '';
            $ar['print_' . $ar['type']] = isset($image->product_print_image) ? $image->product_print_image : '';

            $arr[$print->position_type] = $ar;
        }

        return $arr;
    }

    /**
        获取订单商品资费明细
     */
    function get_order_product_fee_lists($arr, $order_id, $class = 1){
        $lists = [];
        $type  = [1,2,3,4];
        if($class == 2) $type = [1,2,3,4,5];
        $fees  = DB::table('order_detail_fees')
                 ->where(['order_id'    => $order_id,
                          'product_id'  => $arr['product_id'],
                          'colour_name' => $arr['colour_name'],
                          'size_name'   => $arr['size_name'],
                          'state'       =>1])
                 ->whereIn('type', $type)
                 ->select('resource_id','type','title','preferential_price','quantity','thumbnail')
                 ->get()
                 ->toArray();
        foreach($fees as $fee){
            $fee->preferential_price = GeneralTool::priceFormat($fee->preferential_price).'';
            $fee->thumbnail          = isset($fee->thumbnail) ? env('IMG_URL_STD_PREFIX') . $fee->thumbnail : '';
        }
        $lists = $fees;
        return $lists;
    }

    /**
        获取订单产品赠品
     */
    function get_order_product_gift($arr,$order_id){
        $gifts = SQL::get(['table' => 'order_gifts',
                           'where' => ['order_id'    => $order_id,
                                       'product_id'  => $arr['product_id'],
                                       'colour_name' => $arr['colour_name'],
                                       'size_name'   => $arr['size_name'],
                                       'state'       => 1]]);
        foreach($gifts as $gift){
            $gift->thumbnail      = env('IMG_URL_STD_PREFIX').self::getImgPathByImgUrl($gift->thumbnail);
            $gift->original_image = env('IMG_URL_STD_PREFIX').self::getImgPathByImgUrl($gift->original_image);
        }
        return $gifts;
    }

    //判断时间段内是否已催发
    function orderIsUrge($input){
        $count  = DB::table('email_records')
                  ->where(array('reg_id'=>$input['order_id'],
                                'type'=>'order_urge'))
                  ->whereBetween('created_at',array($input['time'], $input['time']+ 3600 * 24))
                  ->count();
        return $count >= env('URGE_ORDER_TIME');
    }

    /**
        发送催单邮件
     */
    function order_email_by_user_urge($input){
        $rex = SQL::first(['table' => 'order_express',
                           'where' => ['order_id' => $input['order_id'],
                                       'state'    => 1]]);
        $total_fee = SQL::pluck(['table' => 'orders',
                                 'where' => ['order_id' => $input['order_id']],
                                 'pluck' => 'total_fee']);
        self::SendToMail(['reg_id'    => $input['order_id'],
                           'type'      => 'order_urge',
                           'rece_user' => env('REMIND_RECE_EMAIL'),
                           'full_name' => isset($rex->consignee)?$rex->consignee:'',
                           'tel'       => isset($rex->phone)?$rex->phone:'',
                           'message'   => '买家催单']);
        self::push_wx(['title'     => '买家催单',
                        'body'      => '详见后台订单详情页面',
                        'total_fee' => (isset($total_fee) ? $total_fee : ''),
                        'name'      => isset($rex->consignee) ? $rex->consignee : '',
                        'phone'     => isset($rex->phone) ? $rex->phone : '',
                        'order_id'  => isset($input['order_id']) ? $input['order_id'] : '']);
        return true;
    }

    /**
        获取订单数
     */
    function get_order_state_count($user_id, $type = 'unpay'){
        $arr['buyer_id'] = $user_id;

        switch($type){
            case 'unpay':
                $arr['state']        = 1;
                $arr['is_cancel']    = 0;
                $arr['is_aftermark'] = 0;
                break;
            case 'unsend':
                $arr['state']        = 2;
                $arr['is_cancel']    = 0;
                $arr['is_aftermark'] = 0;
                break;
            case 'unsign':
                $arr['state']        = 3;
                $arr['is_cancel']    = 0;
                $arr['is_aftermark'] = 0;
                break;
            default:
                return 0;
        }

        return $this->get_order_count($arr);
    }
    /**
        获取订单某一详情
     */
    function get_order_detail_by_order_detail_number($input){
        $detail = SQL::first(['table' => 'order_details',
                              'where' => ['order_detail_number' => $input,
                                          'state'               => 1]]);
        return $detail;
    }

    /**
        物流
     */

    /**
        获取快递物流信息
        参数：
            order_express_id        快递单号
            express_id              快递公司编码
     */
    function getExpress($input){
        $time   = date('Y-m-d H:i:s',time());
        $result = array();
        //判断参数是否足够
        if(empty($input['order_express_id'])||empty($input['express_id'])){
            $result['express_state'] = 0;
            $result['express_state_str'] = $this->getExpressStateStr($result['express_state']);
            $result['data'][]   = (object)array('time'    =>$time,
                                                'ftime'   =>$time,
                                                'context' =>'暂无物流信息');

        }else{
            $express    = SQL::first(array('table'=>'debuglee_express',
                                           'where'=>array('express_company'=>$input['express_id'],
                                                          'express_number'=>$input['order_express_id'])));
            if(isset($express)){
                $result['express_state'] = $express->express_state;
                $result['express_state_str'] = $this->getExpressStateStr($result['express_state']);
                try{
                    $data   = unserialize($express->express_data);

                    $result['data'] = $data;
                }catch(\Expection $e){
                    $result['data'][]   = (object)array('time'=>$time,
                                                'ftime'=>$time,
                                                'context'=>'暂无物流信息');
                    return $result;
                }
            }else{
                $result['express_state'] = 0;
                $result['express_state_str'] = $this->getExpressStateStr($result['express_state']);
                $result['data'][]   = (object)array('time'=>$time,
                                                    'ftime'=>$time,
                                                    'context'=>'暂无物流信息');
            }
        }
        return $result;
    }
    /**
        获取物流状态
     */
    function getExpressStateStr($input){
        $str = '';
        switch($input){
            case 0:
                $str = '在途中';
                return $str;
            case 1:
                $str = '已揽收';
                return $str;
            case 2:
                $str = '疑难';
                return $str;
            case 3:
                $str = '已签收';
                return $str;
            default:

                return $str;
        }
        return $str;
    }
    /**
     *  获取物流列表
     */
    function getExpressList(){
        $result = DB::table('express')
                  ->orderBy('class')
                  ->select('express_id','express_name','class')
                  ->get();
        $arr    = array();
        for($a=0;$a<count($result);$a++){
            if(isset($arr[$result[$a]->class])){
                $arr[$result[$a]->class][]  = $result[$a];
            }else{
                $arr[$result[$a]->class]    = array();
                $arr[$result[$a]->class][]  = $result[$a];
            }

        }
        return $arr;
    }

    /**
        推送
     */
    /**
        下单成功
     */
    static function create_order_success_push($goods, $order, $input){
        try{
            $time                     = self::get_data_from_configs(['name' => 'order_unpay','state' => 1]);
            $time                     = isset($time) ? intval($time / 3600) : '';
            $images['original_image'] = isset($goods['goods']['vaild'][0]->original_image[0]) ?
                                        GeneralTool::clearn_product_image_url($goods['goods']['vaild'][0]->original_image[0]) : '';
            $images['thumbnail']      = isset($goods['goods']['vaild'][0]->thumbnail[0]) ?
                                        GeneralTool::clearn_product_image_url($goods['goods']['vaild'][0]->thumbnail[0]) : '';
            $title                    = '下单成功';
            $message                  = $goods['goods']['vaild'][0]->product_temp_name . '等已下单成功，请尽快完成支付，' . $time . '小时后订单将自动取消';
            $message_in               = $message;
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => $input['user_id'],
                                                          'class'      => 'transaction_information',
                                                          'type'       => 3,
                                                          'jump_value' => $order['result']['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        取消下单
     */
    static function cancel_order_success_push($input, $title_out = '', $message_out = ''){
        try{
            $image      = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images     = ['original_image' => (isset($image['original_image'][0]) ?
                          self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                           'thumbnail'      => (isset($image['thumbnail'][0]) ?
                          self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $title      = '订单取消成功';
            if($title_out != '') $title = $title_out;
            $message    = '订单已取消成功，点击查看详情';
            if($message_out != '') $message = $message_out;
            $message_in = $message;
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => $input['user_id'],
                                                          'class'      => 'transaction_information',
                                                          'type'       => 3,
                                                          'jump_value' => $input['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        运营取消下单
     */
    static function cancel_order_success_push_backstage($input, $title_out = '', $message_out = ''){
        try{
            $image      = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images     = ['original_image' => (isset($image['original_image'][0]) ?
                          self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                           'thumbnail'      => (isset($image['thumbnail'][0]) ?
                          self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $title      = '订单已取消';
            if($title_out != '') $title = $title_out;
            $order     = SQL::first(['table' => 'orders',
                                      'where' => ['order_id' => $input['order_id']]]);
            $message    = '您的订单由于' . (isset($order->cancel_reason) ? $order->cancel_reason : '') .
                          '已被取消，已付金额将原路退回，给您带来的不便，尽情谅解！';
            if($message_out != '') $message = $message_out;
            $message_in = $message;
            JpushTool::push($message,0,$order->buyer_id,['title'      => $title,
                                                          'user_id'    => $order->buyer_id,
                                                          'class'      => 'transaction_information',
                                                          'type'       => 3,
                                                          'jump_value' => $input['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        支付成功
     */
    function pay_order_success_push($input){
        try{
            $input['user_id'] = $this->get_user_id_by_order_id($input['order_id']);
            $image            = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images           = ['original_image' => (isset($image['original_image'][0]) ?
                                 self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                                 'thumbnail'      => (isset($image['thumbnail'][0]) ?
                                 self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $title            = '付款成功';
            $message          = '订单已付款完成，等待卖家发货，点击查看详情';
            $message_in       = $message;
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => (isset($input['user_id']) ? $input['user_id'] : ''),
                                                          'class'      => 'transaction_information',
                                                          'type'       => 3,
                                                          'jump_value' => $input['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        发货order_send_success_push
     */
    function send_order_success_push($input){
        try{

            $input['user_id'] = $this->get_user_id_by_order_id($input['order_id']);
            $image            = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images           = ['original_image' => (isset($image['original_image'][0]) ?
                                self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                                 'thumbnail'      => (isset($image['thumbnail'][0]) ?
                                self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $name             = $this->get_order_first_product_name($input['order_id']);
            $title            = '卖家已发货';
            $message_in       = '你购买的' . $name . '已发货成功，运单编号：' . $input['order_express_id'] .
                                '，快递公司：' . $input['express_name'] . '，请注意查收~';
            $message          = '你购买的' . $name . '已发货成功，运单编号：' . $input['order_express_id'] .
                                '，快递公司：' . $input['express_name'] . '  >>查看详情';
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => (isset($input['user_id']) ? $input['user_id'] : ''),
                                                          'class'      => 'transaction_information',
                                                          'type'       => 2,
                                                          'jump_value' => $input['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        确认收货
     */
    function sign_order_success_push($input){
        try{
            $time             = self::get_data_from_configs(['name' => 'order_after','state' => 1]);
            $time             = isset($time) ? intval($time / (3600 * 24)) : '';
            $input['user_id'] = $this->get_user_id_by_order_id($input['order_id']);
            $image            = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images           = ['original_image' => (isset($image['original_image'][0]) ?
                                self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                                 'thumbnail'      => (isset($image['thumbnail'][0]) ?
                                self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $title            = '订单已确认收货';
            $message          = '订单已确认收货，' . $time . '天内可申请退换货哦。由于定制商品的特殊性，非质量问题都不能退换，请谅解';
            $message_in       = $message;
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => (isset($input['user_id']) ? $input['user_id'] : ''),
                                                          'class'      => 'transaction_information',
                                                          'type'       => 3,
                                                          'jump_value' => $input['order_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        申请售后
     */
    function submit_aftermark_success_push($input){
        try{

            $image            = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images           = ['original_image' => (isset($image['original_image'][0]) ?
                                self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                                 'thumbnail'      => (isset($image['thumbnail'][0]) ?
                                self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];
            $title            = '售后申请已提交';
            $message          = '申请已提交成功，等待审核';
            $message_in       = $message;
            JpushTool::push($message,0,$input['user_id'],['title'      => $title,
                                                          'user_id'    => (isset($input['user_id']) ? $input['user_id'] : ''),
                                                          'class'      => 'transaction_information',
                                                          'type'       => 5,
                                                          'jump_value' => $input['order_after_id'],
                                                          'template_no'=> '3',
                                                          'message'    => $message_in,
                                                          'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }

    /**
        定时
     */

    /**
        付款超时
     */
    static function command_order_unpay_to_cancel(){
        Log::info('----------付款超时处理开始----------');
        $unpay_time = self::get_data_from_configs(['name' => 'order_unpay','state' => 1]);
        if(!isset($unpay_time) || !is_numeric($unpay_time)) return false;
        $end_time   = time() - $unpay_time;
        $orders = DB::table('orders')
                  ->where(['type'         => 'order',
                           'state'        => 1,
                           'is_cancel'    => 0,
                           'is_aftermark' => 0])
                  ->where('created_at','<',$end_time)
                  ->get();
        $total = count($orders);
        $num = 0;
        foreach($orders as $order){
            $cancel = self::order_cancel(['order_id' => $order->order_id,
                                           'user_id'  => $order->buyer_id,
                                           'iden'     => 0]);
            if($cancel != 'M00000') continue;
            $title   = '付款超时';
            $message = '订单付款超时，已自动取消，点击查看详情';
            $push    = self::cancel_order_success_push(['order_id' => $order->order_id,
                                                         'user_id'  => $order->buyer_id],
                                                         $title,
                                                         $message);
            $num++ ;
        }
        Log::info('付款超时处理结果: 应取消订单数--' . $total . ', 本次取消订单数--' . $num);
        Log::info('----------付款超时处理结束----------');
        return true;
    }

    /**
        待付款提醒
     */
    static function command_order_unpay_remind(){
        Log::info('----------待付款提醒处理开始----------');
        $unpay_remind_time = self::get_data_from_configs(['name' => 'order_unpay_remind','state' => 1]);
        if(!isset($unpay_remind_time) || !is_numeric($unpay_remind_time)) return false;
        $end_time   = time() - $unpay_remind_time;
        $orders = DB::table('orders')
                  ->where(['type'           => 'order',
                           'state'          => 1,
                           'is_cancel'      => 0,
                           'is_aftermark'   => 0,
                           'is_remind_push' => 0])
                  ->where('created_at','<',$end_time)
                  ->get();
        $total = count($orders);
        $num = 0;
        foreach($orders as $order){
            $result  = SQL::update(['table' => 'orders',
                                    'where' => ['order_id' => $order->order_id],
                                    'update'=> ['is_remind_push' => 1]]);
            $title   = '未付款提醒';
            $message = '【提醒】你有单待付款订单将在' . ($unpay_remind_time / 3600) . '小时后自动取消 >>查看详情';
            $message_in = '订单将在' . ($unpay_remind_time / 3600) . '小时后自动取消，点击查看详情';
            $push    = self::push(['order_id'   => $order->order_id,
                                   'user_id'    => $order->buyer_id,
                                   'title'      => $title,
                                   'message'    => $message,
                                   'message_in' => $message_in]);
            $num++ ;
        }
        Log::info('待付款提醒处理结果: 应提醒订单数--' . $total . ', 本次提醒订单数--' . $num);
        Log::info('----------待付款提醒处理结束----------');
        return true;
    }

    /**
        待收货提醒
     */
    static function command_order_unsign_remind(){
        Log::info('----------待收货提醒处理开始----------');
        $unsign_remind_time = self::get_data_from_configs(['name' => 'order_unsign_remind','state' => 1]);
        if(!isset($unsign_remind_time) || !is_numeric($unsign_remind_time)) return false;
        $end_time   = time() - $unsign_remind_time;
        $orders = DB::table('orders')
                  ->where(['type'           => 'order',
                           'state'          => 3,
                           'is_cancel'      => 0,
                           'is_aftermark'   => 0])
                  ->get();
        $total = 0;
        $num = 0;
        foreach($orders as $order){
            //获取订单需要发送收获提醒的发货操作id
            $id = DB::table('order_operations')
                  ->where(['order_id'         => $order->order_id,
                           'over_order_state' => 3,
                           'order_state'      => 2,
                           'is_push'          => 0])
                  ->where('created_at', '<', $end_time)
                  ->value('id');
            if(!isset($id)) continue;
            $total++ ;
            $result  = SQL::update(['table' => 'order_operations',
                                    'where' => ['id'      => $id],
                                    'update'=> ['is_push' => 1]]);
            if(!$result) continue;

            $title   = '待收货提醒';
            $message = '订单将在' . ($unsign_remind_time / 86400) . '天后自动确认收货，请及时确认~点击查看详情';
            $message_in = '订单将在' . ($unsign_remind_time / 86400) . '天后自动确认收货，请及时确认~点击查看详情';
            $push    = self::push(['order_id'   => $order->order_id,
                                   'user_id'    => $order->buyer_id,
                                   'title'      => $title,
                                   'message'    => $message,
                                   'message_in' => $message_in]);
            $num++ ;
        }
        Log::info('待收货提醒处理结果: 应提醒订单数--' . $total . ', 本次提醒订单数--' . $num);
        Log::info('----------待收货提醒处理结束----------');
        return true;
    }

    /**
        待收货超时
     */
    static function command_order_unsign_to_sign(){
        Log::info('----------待收货超时处理开始----------');
        $unsign_remind_time = self::get_data_from_configs(['name' => 'order_unsign','state' => 1]);
        if(!isset($unsign_remind_time) || !is_numeric($unsign_remind_time)) return false;
        $end_time   = time() - $unsign_remind_time;
        $orders = DB::table('orders')
                  ->where(['type'           => 'order',
                           'state'          => 3,
                           'is_cancel'      => 0,
                           'is_aftermark'   => 0])
                  ->get();
        $total = 0;
        $num = 0;
        foreach($orders as $order){
            //获取订单需要发送收获提醒的发货操作id
            $id = DB::table('order_operations')
                  ->where(['order_id'         => $order->order_id,
                           'over_order_state' => 3,
                           'order_state'      => 2])
                  ->where('created_at', '<', $end_time)
                  ->value('id');
            if(!isset($id)) continue;
            $total++ ;
            $result  = self::order_sign(['order_id' => $order->order_id,
                                          'user_id' => $order->buyer_id,
                                          'iden'     => 0]);
            if($result != 'M00000') continue;

            $title   = '收货超时';
            $message = '订单已自动确认收货，点击查看详情';
            $message_in = '订单已自动确认收货，点击查看详情';
            $push    = self::push(['order_id'   => $order->order_id,
                                   'user_id'    => $order->buyer_id,
                                   'title'      => $title,
                                   'message'    => $message,
                                   'message_in' => $message_in]);
            $num++ ;
        }
        Log::info('待收货超时处理结果: 应提醒订单数--' . $total . ', 本次提醒订单数--' . $num);
        Log::info('----------待收货超时处理结束----------');
        return true;
    }

    /**
        关闭订单定时
     */
    static function command_order_close(){
        Log::info('----------关闭订单处理开始----------');
        $order_after_time = self::get_data_from_configs(['name' => 'order_after','state' => 1]);
        if(!isset($order_after_time) || !is_numeric($order_after_time)) return false;
        $end_time   = time() - $order_after_time;
        $orders = DB::table('orders')
                  ->where(['type'           => 'order',
                           'pay_state'      => 2,
                           'is_cancel'      => 0,
                           'is_aftermark'   => 0,
                           'is_close'       => 0])
                  ->whereIn('state',[0,4])
                  ->get()
                  ->toArray();

        $total = 0;
        $num = 0;
        foreach($orders as $order){
            //判断订单是否可以关闭
            $id = DB::table('order_operations')
                  ->where(['order_id'         => $order->order_id,
                           'order_state'      => 3,
                           'over_order_state' => 4])
                  ->where('created_at', '<', $end_time)
                  ->value('id');

            if(!isset($id)) continue;
            $total++ ;
            try{
                SQL::FirstDo();
                $result  = self::order_close($order);
                if($result != 'M00000') continue;

                self::deal_with_by_order_detail_fee(['order_id' => $order->order_id]);
                $num++ ;
            }catch(\Exception $e){
                Log::info($e);
                SQL::CatchDo();
            }finally{
                SQL::FinallyDo();
            }



        }
        Log::info('关闭订单处理结果: 应关闭订单数--' . $total . ', 本次关闭订单数--' . $num);
        Log::info('----------关闭订单处理结束----------');
        return true;
    }

    /**
     * 待发货订单8小时未进行确认 定时邮件提醒
     */
    static function order_confirm_remind(){
        $orders = SQL::lists(['table' => 'orders',
                              'where' => ['state'      => 2,
                                          'is_confirm' => 0],
                              'lists'  => 'order_id']);
        if(count($orders) == 0) return false;
        $time = time();
        $orders = DB::table('order_operations')
                  ->where(['over_order_state' => 2,
                           'is_close'    => 0])
                  ->whereIn('order_id', $orders)
                  ->where('created_at', '<', ($time - env('UNCONFIRM_REMIND_TIME')))
                  ->pluck('order_id')
                  ->toArray();
        $long = env('UNCONFIRM_REMIND_TIME_LONG');
        $num  = 0;
        foreach($orders as $one){
            if(isset($long) && is_numeric($long) && self::order_can_send_email($one, intval($long), 'order_confirm_remind')) continue;
            $num++;
            $rex = SQL::first(['table' => 'order_express',
                               'where' => ['order_id' => $one,
                                           'state'    => 1]]);
            $total_fee = SQL::pluck(['table' => 'orders',
                                     'where' => ['order_id' => $one],
                                     'pluck' => 'total_fee']);
            self::SendToMail(['reg_id'    => $one,
                              'type'      => 'order_confirm_remind',
                              'rece_user' => env('REMIND_RECE_EMAIL'),
                              'full_name' => isset($rex->consignee)?$rex->consignee:'',
                              'tel'       => isset($rex->phone)?$rex->phone:'',
                              'message'   => '订单等待发货已超过' . intval(env('UNCONFIRM_REMIND_TIME')/3600) . '小时未确认,请及时处理']);
            self::push_wx(['title'     => '订单等待发货已超过' . intval(env('UNCONFIRM_REMIND_TIME')/3600) . '小时未确认,请及时处理',
                            'body'      => '详见后台订单详情页面',
                            'total_fee' => (isset($total_fee) ? $total_fee : ''),
                            'name'      => isset($rex->consignee) ? $rex->consignee : '',
                            'phone'     => isset($rex->phone) ? $rex->phone : '',
                            'order_id'  => isset($one) ? $one : '']);
        }
        return $num;
    }

    /**
     * 已确认订单N小时未进行发货 定时邮件提醒
     */
    static function order_unsend_remind(){
        $orders = DB::table('orders')
                  ->where(['state'      => 2,
                           'is_confirm' => 1])
                  ->where('confirm_time', '<', (time() - env('CONFIRM_UNSEND_REMIND_TIME')))
                  ->pluck('order_id');
        if(count($orders) == 0) return false;

        $long = env('CONFIRM_UNSEND_REMIND_TIME_LONG');
        foreach($orders as $one){
            if(isset($long) && is_numeric($long) && self::order_can_send_email($one, $long, 'order_unsend_remind')) continue;
            $rex = SQL::first(['table' => 'order_express',
                               'where' => ['order_id' => $one,
                                           'state'    => 1]]);
            $total_fee = SQL::pluck(['table' => 'orders',
                                     'where' => ['order_id' => $one],
                                     'pluck' => 'total_fee']);
            self::SendToMail(['reg_id'    => $one,
                              'type'      => 'order_unsend_remind',
                              'rece_user' => env('REMIND_RECE_EMAIL'),
                              'full_name' => isset($rex->consignee)?$rex->consignee:'',
                              'tel'       => isset($rex->phone)?$rex->phone:'',
                              'message'   => '订单确认后已超过' . intval(env('UNCONFIRM_REMIND_TIME')/3600) . '小时物流信息未变化,请及时处理']);
            self::push_wx(['title'      => '订单确认后已超过' . intval(env('UNCONFIRM_REMIND_TIME')/3600) . '小时物流信息未变化,请及时处理',
                            'body'      => '详见后台订单详情页面',
                            'total_fee' => (isset($total_fee) ? $total_fee : ''),
                            'name'      => isset($rex->consignee) ? $rex->consignee : '',
                            'phone'     => isset($rex->phone) ? $rex->phone : '',
                            'order_id'  => isset($one) ? $one : '']);
        }
        return true;
    }


    /**
        工具
     */

    /**
     * 判断是否可发邮件
     */
    static function order_can_send_email($reg_id, $long, $type){
        $created_at = DB::table('email_records')
                      ->where(['reg_id' => $reg_id,
                               'type'   => $type])
                      ->value('created_at');
        if(!isset($created_at) || time() - $long > $created_at) return false;
        return true;
    }

    /**
        获取订单第一件商品名称
     */
    function get_order_first_product_name($order_id){
        $detail = SQL::first(['table' => 'order_details',
                              'where' => ['order_id' => $order_id]]);
        return isset($detail->product_temp_name) ? $detail->product_temp_name : '';
    }

    static function push($input){
        try{
            $image            = self::get_order_first_picture(['order_id' => $input['order_id']]);
            $images           = ['original_image' => (isset($image['original_image'][0]) ?
                                self::getImgPathByImgUrl($image['original_image'][0]) : ''),
                                 'thumbnail'      => (isset($image['thumbnail'][0]) ?
                                self::getImgPathByImgUrl($image['thumbnail'][0]) : '')];

            JpushTool::push($input['message'],0,$input['user_id'],['title'      => $input['title'],
                                                                   'user_id'    => (isset($input['user_id']) ? $input['user_id'] : ''),
                                                                   'class'      => 'transaction_information',
                                                                   'type'       => 3,
                                                                   'jump_value' => $input['order_id'],
                                                                   'template_no'=> '3',
                                                                   'message'    => $input['message_in'],
                                                                   'images'     => [$images]]);
        }catch(\Exception $e){
            Log::info($e);
        }
    }


    /**
        backstage
     */

    /**
     * 筛选订单
       参数：
            order_id    订单号         orders
            state       订单状态       orders
            time_range  下单时间范围    orders
            pay_type    支付方式       orders
            platform    平台           orders
            consignee   收货人         order_express
            address     详细地址       order_express
            phone       电话           order_express
            express_id  配送方式       order_express
     */
    function order_list_lists_backstage($input){
        $lists   = [];
        if(isset($input['order_express'])){

            $express = $this->order_list_get_order_id_lists_backstage_by_order_express($input['order_express']);
            $lists   = array_merge($lists, $express);
            $lists   = array_unique($lists);

            $orders  = $this->order_list_only_orders_from_orders($input,$lists);
        }else{
            $orders  = $this->order_list_only_orders_from_orders($input);
        }
        return $orders;
    }


    /**
        orders表获取订单列表
     */
    function order_list_only_orders_from_orders($input, $order_id = [], $per_page = 10){
        $date_range_picker = isset($input['orders']['time_range'])?$input['orders']['time_range']:'01/01/2015 - 12/30/2025';

        $from_time = substr(trim($date_range_picker),0,strpos(trim($date_range_picker),'-')-1);
        $to_time   = substr(trim($date_range_picker),strpos(trim($date_range_picker),'-')+2);
        $from_time = strtotime($from_time.' 00:00:00') ? strtotime($from_time.' 00:00:00') : strtotime('01/01/2015'.' 00:00:00');
        $to_time   = strtotime($to_time.' 23:59:59') ? strtotime($to_time.' 23:59:59') : strtotime('12/30/2025'.' 00:00:00');
        if(isset($input['orders']['time_range'])) unset($input['orders']['time_range']);
        $input['orders'] = isset($input['orders']) ? $input['orders'] : [];
        if(!is_array($order_id) || count($order_id) == 0){
            $orders = DB::table('orders')
                      ->where($input['orders'])
                      ->whereBetween('created_at', [$from_time, $to_time])
                      ->orderBy('created_at','desc')
                      ->select('order_id', 'buyer_id', 'total_fee', 'is_cancel', 'state', 'platform', 'created_at')
                      ->paginate($per_page);
        }else{
            $orders = DB::table('orders')
                      ->where($input['orders'])
                      ->whereIn('order_id',$order_id)
                      ->whereBetween('created_at', [$from_time, $to_time])
                      ->orderBy('created_at','desc')
                      ->select('order_id', 'buyer_id', 'total_fee', 'is_cancel', 'state', 'platform', 'created_at')
                      ->paginate($per_page);

        }

        foreach($orders as $order){
            $order->rece        = $this->get_order_receiving($order->order_id);
            $order->total_price = $this->get_order_total_price($order->order_id);
        }
        return $orders;
    }

    /**
        orders数据统计
     */
    function order_statistics($input, $order_id = []){

        $input['orders'] = isset($input['orders']) ? $input['orders'] : [];
        $db = new ODB('orders');

        $time      = explode(',',$input['time_range']);
        $all       = [];
        $unpay     = [];
        $pay       = [];
        $complete  = [];
        $cancel    = [];
        $aftermark = [];
        $title     = [];
        for($a = 1; $a < count($time) - 1; $a++){
            $where                 = $input['orders'];
            $db->where($where, 1);
            $begin                 = strtotime($time[$a]);
            $end                   = strtotime($time[$a + 1]);
            //下表
            $title[]               = $time[$a];
            //所有
            $db->whereBetween(['created_at',[$begin,$end]], 1);
            $all[]                 = $db->count();
            //未支付
            $where['state']        = 1;
            $db->where($where, 1);
            $unpay[]               = $db->count();
            //已支付
            $where                 = $input['orders'];
            $where['pay_state']    = 2;
            $db->where($where, 1);
            $pay[]                 = $db->count();
            //已完成
            $where                 = $input['orders'];
            $where['pay_state']    = 4;
            $db->where($where, 1);
            $complete[]            = $db->count();
            //已取消
            $where                 = $input['orders'];
            $where['is_cancel']    = 1;
            $db->where($where, 1);
            $cancel[]              = $db->count();
            //申请售后
            $where                 = $input['orders'];
            $where['is_aftermark'] = 1;
            $db->where($where, 1);
            $aftermark[]           = $db->count();
        }
        return [
                    'title' => $title,
                    'all'   => $all,
                    'unpay' => $unpay,
                    'pay'   => $pay,
                    'complete' => $complete,
                    'cancel' => $cancel,
                    'aftermark' => $aftermark
                ];
    }

    /**
        订单详情
     */
    function order_detail_backstage($order_id){
        $order  = SQL::first(['table' => 'orders',
                              'where' => ['order_id' => $order_id]]);
        if(!isset($order)) return (object)[];
        $detail                 = $this->get_order_detail_goods_from_list($order_id, 3);
        $order->express         = $this->get_order_receiving($order_id, 2);
        $order->coupon          = $this->get_order_coupon($order_id);
        $order->detail          = $detail;
        $order->pay_time_str    = $this->get_order_operation_time($order->order_id,'pay');
        $order->send_time_str   = $this->get_order_operation_time($order->order_id,'send');
        $order->sign_time_str   = $this->get_order_operation_time($order->order_id,'sign');
        $order->cancel_time_str = $this->get_order_operation_time($order->order_id,'cancel');
        $order->cancel          = SQL::first(['table' => 'order_operations',
                                              'where' => ['order_id' => $order_id,
                                                          'is_cancel'=>1]]);
        $order->order_after_id  = $order->is_aftermark ? $this->get_order_after_id_now($order->order_id) : '';
        $order->discount_price  = isset($order->channel_id) && $order->channel_id != '' ?
                                  ($detail['total_price'] - $order->total_fee) : $this->get_order_discount_price($order->order_id);
        $order->operations      = [];

        return $order;
    }

    /**
        修改订单物流信息
     */
    function order_send($order, $input){
        $state = 'M00003';
        SQL::FirstDo();
        try{
            //判断订单是否已发货
            if($order->send_state == 0){
                //未发货
                //修改订单状态
                $result = $this->order_send_goods($order);
                if($result != 'M00000'){
                    $state = $result;
                    Throw new \Exception('订单发货处理失败');
                }
                $this->send_order_success_push($input);
            }

            //更新物流信息
            $express = SQL::update(['table' => 'order_express',
                                    'where' => ['order_id' => $input['order_id'],
                                                'state'    => 1],
                                    'update'=> ['express_id'       => $input['express_id'],
                                                'express_name'     => $input['express_name'],
                                                'order_express_id' => $input['order_express_id']]]);
            return 'M00000';
        }catch(\Exception $e){
            Log::info($e);
            SQL::CatchDo();
            return $state;
        }finally{
            SQL::FinallyDo();
        }
    }

    /**
        获取订单zip打印图数据
     */
    function get_order_prints_to_zip($order_id){
        $detail = SQL::get(['table' => 'order_details',
                            'where' => ['order_id' => $order_id,
                                        'state'    => 1]]);
        $arr    = [];
        foreach($detail as $det){
            $print = $this->get_order_product_prints($det, $order_id);
            $arr[$det->order_detail_number.''] = $print;

        }
        return $arr;
    }

    /**
        修改订单收获信息
     */
    function update_order_rece($input){
        $result = SQL::update(['table' => 'order_express',
                               'where' => ['order_id' => $input['order_id'],
                                           'state'    => 1],
                               'update'=> ['consignee' => $input['consignee'],
                                           'phone'     => $input['phone'],
                                           'address'   => $input['address']]]);
        return $result ? 'M00000' : 'M00001';
    }

    /**
        获取生存Excel订单数据
     */
    function order_list_lists_from_excel($input, $order_id = []){
        $date_range_picker = isset($input['orders']['time_range'])?$input['orders']['time_range']:'01/01/2015 - 12/30/2025';

        $from_time = substr(trim($date_range_picker),0,strpos(trim($date_range_picker),'-')-1);
        $to_time   = substr(trim($date_range_picker),strpos(trim($date_range_picker),'-')+2);
        $from_time = strtotime($from_time.' 00:00:00') ? strtotime($from_time.' 00:00:00') : strtotime('01/01/2015'.' 00:00:00');
        $to_time   = strtotime($to_time.' 23:59:59') ? strtotime($to_time.' 23:59:59') : strtotime('12/30/2025'.' 00:00:00');
        if(isset($input['orders']['time_range'])) unset($input['orders']['time_range']);
        $input['orders'] = isset($input['orders']) ? $input['orders'] : [];
        $rows      = [];
        if(!is_array($order_id) || count($order_id) == 0){
            $orders = DB::table('orders')
                      ->where($input['orders'])
                      ->whereBetween('created_at', [$from_time, $to_time])
                      ->orderBy('created_at','desc')
                      ->select('order_id', 'buyer_id', 'total_fee', 'pay_type', 'is_cancel', 'state', 'platform', 'created_at')
                      ->get()
                      ->toArray();
        }else{
            $orders = DB::table('orders')
                      ->where($input['orders'])
                      ->whereIn('order_id',$order_id)
                      ->whereBetween('created_at', [$from_time, $to_time])
                      ->orderBy('created_at','desc')
                      ->select('order_id', 'buyer_id', 'total_fee', 'pay_type', 'is_cancel', 'state', 'platform', 'created_at')
                      ->get()
                      ->toArray();
        }

        foreach($orders as $order){
            $order->rece        = $this->get_order_receiving($order->order_id);
            $order->total_price = $this->get_order_total_price($order->order_id);
            $order->goods_str   = $this->get_order_goods_str($order->order_id);
            $order->coupon      = $this->get_order_coupon($order->order_id);
            $row['订单编号']     = $order->order_id;
            $row['订单总金额']   = $order->total_price;
            $row['订单实际支付金额'] = $order->total_fee;
            $row['优惠抵扣金额'] = isset($order->coupon->coupon_price) ? $order->coupon->coupon_price : '';
            $row['支付类型']     = $this->get_pay_type_str($order->pay_type);
            $row['商品信息']     = $order->goods_str;
            $row['收货人姓名']   = isset($order->rece->consignee) ? $order->rece->consignee : '';
            $row['联系电话']     = isset($order->rece->phone) ? $order->rece->phone : '';
            $row['详细地址']     = isset($order->rece->address) ? $order->rece->address : '';
            $row['创建时间']     = isset($order->created_at) ? date('Y-m-d H:i:s',$order->created_at) : '';
            $row['支付时间']     = $this->get_order_operation_time($order->order_id,'pay');
            $rows[] = $row;
        }

        return $rows;
    }

    /**
        生产订单Excel
     */
    function create_order_excel($rows){
        //判断文件夹是否存在
        if(!is_dir(public_path('images'.DIRECTORY_SEPARATOR.'excel')))
            mkdir(public_path('images'.DIRECTORY_SEPARATOR.'excel'));
        if(!is_dir(public_path('images'.DIRECTORY_SEPARATOR.'excel'.DIRECTORY_SEPARATOR.'order')))
            mkdir(public_path('images'.DIRECTORY_SEPARATOR.'excel'.DIRECTORY_SEPARATOR.'order'));
        $time                           = time();
        Excel::create($time, function($excel) use ($rows) {
            $excel->sheet('order', function($sheet) use ($rows) {
                $sheet->fromArray($rows);
            });
        })->store('xls', public_path('images'.DIRECTORY_SEPARATOR.'excel'.DIRECTORY_SEPARATOR.'order'));
        return ['url' => asset('images/excel/order/'.$time.'.xls')];
    }

    /**
     * 获取生成订单商品详情
     */
    function get_order_detail_to_create($input){

        $detail = json_decode($input['detail']);
        if(!$detail) return ['state' =>  'M00004'];
        $arr['total_postage'] = 0;
        $arr['total_fee'] = 0;
        $vaild                    = [] ;
        $unvaild                  = [] ;
        foreach($detail as $det){
            if(!isset($det->product_id) ||
                !isset($det->colour_name) ||
                !isset($det->size_name) ||
                !isset($det->quantity))
                return ['state' => 'M05065'];
            $det->user_id = $input['user_id'];
            $det->product_temp_id = $this->carTool->getTemplateByProductId($det->product_id);
            $good = $this->carTool->get_product_info($det,2);
            $arr['total_fee'] += $good->preferential_price * $det->quantity;
            if(isset($good->is_sale) && $good->is_sale){
                $vaild[] = $good;
                if(isset($good->postage)) $arr['total_postage'] += $good->postage ;
                if(isset($good->is_select) && !$good->is_select) $is_all_select = 0;
            }else{
                $unvaild[] = $good;
            }
        }
        $arr['goods'] = ['vaild'   => $vaild,'unvaild' => $unvaild];
        $arr['state'] = 'M00000';
        return $arr;
    }

    /**
        订单详情处理
     */
    function order_details_from_backstage($shop_car,$arr){

        foreach($shop_car['goods']['vaild'] as $good){
            //order_details
            $order_details = $this->insert_order_details($good,$arr,2);
            if($order_details['state'] != 'M00000') return $order_details;
            //order_detail_print
            $order_detail_print = $this->order_detail_print($good,$arr,2);
            if($order_detail_print != 'M00000') return GeneralTool::createResult('',$order_detail_print);
            //order_detail_fee
            $order_detail_fee = $this->order_detail_fee($good,$arr);
            if($order_detail_fee != 'M00000') return GeneralTool::createResult('',$order_detail_fee);
        }

        return GeneralTool::createResult('','M00000');
    }

    /**
        工具
     */

    /**
        获取支付字符串
     */
    private function get_pay_type_str($type){
        switch($type){
            case 1:
                return '微信';
            case 2:
                return '支付宝';
            case 3:
                return '优惠券';
            default:
                return '未支付';
        }
    }
    /**
        获取商品字符串
     */
    private function get_order_goods_str($order_id){
        $str = '';
        $details = DB::table('order_details')
                   ->where(['order_id' => $order_id,
                            'state'    => 1])
                   ->select('product_id','product_temp_name','brand_name','quantity','colour_name','size_name','preferential_price','postage')
                   ->get()
                   ->toArray();
        foreach($details as $detail){
            $str .= '产品模版名称:' . $detail->product_temp_name . ','.
                    '品牌:' . $detail->brand_name . ',' .
                    '眼色:' . $detail->colour_name . ',' .
                    '尺码:' . $detail->size_name . ',' .
                    '数量:' . $detail->quantity . ',' .
                    '单价:' . $detail->preferential_price . ',' .
                    '邮费:' . $detail->postage . ' , ' .
                    '赠品:' . $this->get_order_gifts_str($detail,$order_id) . '|';
        }
        return $str;
    }
    /**
        获取赠品字符串
     */
    private function get_order_gifts_str($detail, $order_id){
        $str = '';
        $gifts = DB::table('order_gifts')
                 ->where(['order_id'    => $order_id,
                          'colour_name' => $detail->colour_name,
                          'size_name'   => $detail->size_name,
                          'product_id'  => $detail->product_id,
                          'state'       => 1])
                 ->select('name','quantity')
                 ->get()
                 ->toArray();
        foreach($gifts as $gift){
            $str  .= '名称:' . (isset($gift->name)? $gift->name : '') . ',' .
                     '数量:' . (isset($gift->quantity) ? $gift->quantity : '') . ';';
        }
        return $str;
    }
    /**
        筛选order_express
     */
    private function order_list_get_order_id_lists_backstage_by_order_express($input){

        $order_id = DB::table('order_express')
                    ->where($input)
                    ->pluck('order_id')
                    ->toArray();
        return $order_id;

    }

    /**
        获取订单优惠券对象
     */
    private function get_order_coupon($order_id){
        $coupon = SQL::first(['table' => 'order_coupons',
                              'where' => ['order_id' => $order_id,
                                          'state'    => 1]]);
        if(!isset($coupon)) return (object)[];
        return $coupon;
    }

    /**
        获取订单总金额
     */
    function get_order_total_price($order_id){
        $lists = DB::table('order_details')
                 ->where(['order_id' => $order_id,
                          'state'    => 1])
                 ->select('preferential_price', 'quantity')
                 ->get();
        $total_price = 0;
        foreach($lists as $list){
            $total_price += $list->preferential_price * $list->quantity;
        }
        return $total_price;
    }

    /**
        获取订单当前售后单编号
     */
    function get_order_after_id_now($order_id){
        $after = DB::table('order_aftermarks')
                 ->where(['order_id' => $order_id])
                 ->orderBy('created_at','desc')
                 ->first();
        return isset($after->order_after_id) ? $after->order_after_id : '';
    }



    /**
     * 微信推送
     * @param  [type] $input [description]
     * @return [type]        [description]
     */
    static function push_wx($input){
        $input['template_id'] = isset($input['template_id']) ? $input['template_id'] : env('ORDER_PAY_TEMPLATE_WX');
        $open = explode(',',env('ORDER_RECE_OPENID'));
        foreach($open as $open_id){
            $input['open_id'] = $open_id;
            WxTemplate::send($input);
        }
    }

    function test($input){


    }

    /**
        other
     */
    /**
        是否为用户
     */
    function isUser($input){
        return $this->userTool->isUser($input);
    }
    /**
        收货地址编号获取收货地址信息
     */
    function addressByID($address_id,$user_id){
        return $this->userTool->addressByID($address_id,$user_id);
    }
    /**
        减产品模版库存
     */
    function tempDecrementStock($product_temp_id, $colour_name, $size_name, $num){
        return $this->productTempTool->decrementStock($product_temp_id, $colour_name, $size_name, $num);
    }
    /**
        增加产品模版库存
     */
    static function tempIncrementStock($product_temp_id, $colour_name, $size_name, $num){
        return ProductTempTool::incrementStock($product_temp_id, $colour_name, $size_name, $num);
    }
    /**
        增加商品库存
     */
    static function product_stock_change($product_id, $num, $type){
        return ProductTool::product_stock_change($product_id, $num, $type);
    }
    /**
        增加赠品库存
     */
    static function giftIncrementStock($gift_id, $num){
        return GiftApiService::incrementStock($gift_id, $num);
    }
    /**
        减赠品库存
     */
    function giftDecrementStock($gift_id, $num){
        return $this->giftApiService->decrementStock($gift_id, $num);
    }
    /**
        产品编号获取模版编号
     */
    function getTemplateByProductId($input){
        return $this->productTool->getTemplateByProductId($input);
    }
    /**
        商品是否可购买
     */
    function can_order($product_id, $colour_name, $size_name, $quantity, $user_id){
        return $this->productTool->can_order($product_id, $colour_name, $size_name, $quantity, $user_id);
    }
    /**
     * 活动判断作品是否可买
     */
    function can_order_for_activity($product_id, $colour_name, $size_name, $quantity, $user_id){
        return $this->productTool->can_order_for_activity($product_id, $colour_name, $size_name, $quantity, $user_id);
    }
    /**
        增加素材已售
     */
    function updateSourcePicUsedNum($source_pic_id, $num){
        return $this->sourceTool->updateSourcePicUsedNum($source_pic_id, $num);
    }
    /**
        增加商品已售
     */
    function product_sell_num($product_id, $num, $type = 1){
        return $this->productTool->product_sell_num($product_id, $num, $type);
    }
    /**
        增加用户销量
     */
    function addSellNum($user_id, $sell_num){
        return $this->userTool->AddSellNum($user_id, $sell_num);
    }
    /**
        截取图片链接
     */
    static function getImgPathByImgUrl($input){
        return ImgTool::getImgPathByImgUrl($input);
    }
    /**
        打印图id获取打印图对象
     */
    function get_product_preview_images_by_id($input){
        return $this->productTool->get_product_preview_images_by_id($input);
    }
    /**
     * 产品模版编获取产品模版
     */
    function getProductTempByProductTempId($input){
        return ProductTempTool::getProductTempByProductTempId($input);
    }
    /**
     * 获取产品模版颜色数组
     */
    function productTempColoursByProductTempId($input){
        return ProductTempTool::productTempColoursByProductTempId($input);
    }
    /**
     * 获取产品模版颜色对应尺码
     */
    function getProductTempSizeNamesByProductTempIdAndColourId($product_temp_id,$colour_id){
        return ProductTempTool::getProductTempSizeNamesByProductTempIdAndColourId($product_temp_id,$colour_id);
    }
    /**
     * 获取产品模版颜色对应打印位
     */
    function productTempCustomZonePositionNamesByTempId($temp_id,$colour_id){
        return ProductTempTool::productTempCustomZonePositionNamesByTempId($temp_id,$colour_id);
    }
    /**
     * 判断模版是否可买
     */
    function isCanBuyTempByAcualStock($product_temp_id,$colour_name,$size_name,$num){
        return ProductTempTool::isCanBuyTempByAcualStock($product_temp_id,$colour_name,$size_name,$num);
    }
}
